package main

import (
	"example_shop/kitex_gen/example/shop/item"
	"example_shop/kitex_gen/example/shop/item/itemservice"
	"example_shop/kitex_gen/example/shop/stock"
	"example_shop/kitex_gen/example/shop/stock/stockservice"
	"github.com/cloudwego/kitex/client"
	"github.com/cloudwego/kitex/client/callopt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

var itemCli itemservice.Client
var stockCli stockservice.Client

func init() {
	var err error
	itemCli, err = itemservice.NewClient("example.shop.item", client.WithHostPorts("0.0.0.0:10002"))
	if err != nil {
		panic(err)
	}

	stockCli, err = stockservice.NewClient("example.shop.stock", client.WithHostPorts("0.0.0.0:10003"))
	if err != nil {
		panic(err)
	}
}

func main() {
	r := gin.Default()
	r.GET("/item", itemHandler)
	r.GET("/stock", stockHandler)
	err := r.Run(":10001")
	if err != nil {
		return
	}
}

func itemHandler(c *gin.Context) {
	id, err := strconv.ParseInt(c.Query("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"})
		return
	}

	req := item.NewGetItemReq()
	req.SetId(id)
	resp, err := itemCli.GetItem(c, req, callopt.WithRPCTimeout(3*time.Second))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, resp)
}

func stockHandler(c *gin.Context) {
	req := stock.NewGetItemStockReq()
	resp, err := stockCli.GetItemStock(c, req, callopt.WithRPCTimeout(3*time.Second))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, resp)
}
